package com.jiantong.version.impl.service;

import com.google.common.base.Throwables;
import com.jiantong.version.enums.InstallationPackageType;
import com.jiantong.version.impl.dao.VersionControlDao;
import com.jiantong.version.model.VersionControl;
import com.jiantong.version.service.VersionControlReadService;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by niufei on 2017/4/26.
 *
 */
@Slf4j
@Service
@RpcProvider
public class VersionControlReadServiceImpl implements VersionControlReadService {

    private final VersionControlDao versionControlDao;

    @Autowired
    public VersionControlReadServiceImpl(VersionControlDao versionControlDao) {
        this.versionControlDao = versionControlDao;
    }

    @Override
    public Response<VersionControl> findByType(Integer type) {
        try{
            VersionControl versionControl;
            if(type.equals(InstallationPackageType.ANDROID.value())){
                versionControl = versionControlDao.findById(1);
            }else{
                versionControl = versionControlDao.findById(2);
            }
            if(versionControl == null){
                log.error("failed.to.find.version: type = {} ,case = {}" ,type);
                return Response.fail("failed.to.find.version");
            }
            return Response.ok(versionControl);
        }catch (Exception e){
            log.error("failed.to.find.version: case = {}" ,type, Throwables.getStackTraceAsString(e));
            return Response.fail("failed.to.find.version");
        }
    }

    @Override
    public Response<VersionControl> findById(Long id) {
        try{
            return Response.ok(versionControlDao.findById(id));
        }catch (Exception e){
            log.error("failed.to.find.version: id = {} ,case = {}" ,id, Throwables.getStackTraceAsString(e));
            return Response.fail("failed.to.find.version");
        }
    }

    @Override
    public Response<List<VersionControl>> queryList() {
        try {
            return Response.ok(versionControlDao.queryList());
        }catch (Exception e){
            log.error("failed to query version control list");
            return Response.fail("failed to query version control list");
        }
    }
}
